#!/bin/bash
###
# @author("Raymond Blum" <raymond@insanegiantrobots.com>)
# Copyright (c) 2013 by Raymond Blum
# This software is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# Use at your own risk
#
# root $ crontab -l
# ...
# Check and try to reestablish the network connection every minute
# Add into root's crontab:
# * * * * * /usr/local/bin/maintain-network.sh
###
#
CMD=$(basename $0);TMPFILE=$(mktemp -t $CMD.XXXX)
# Try to ping your router, not an external address as if there are
# problems on the other side of the router, we cannot fix that from
# here so there's no sense in trying.
PINGTARGET="192.168.0.3"
/bin/ping -c 1 ${PINGTARGET} 2>&1 > ${TMPFILE}
RC=$?
if [[ $RC -ne 0 ]];then
  logger "network down"
  cat ${TMPFILE} | logger
  /etc/init.d/networking restart | logger
  /bin/ping -c 1 ${PINGTARGET} 2>&1 > ${TMPFILE}
  RC=$?
  if [[ $RC -ne 0 ]];then
    logger "network still down"
    if [[ -f /tmp/downfile ]];then
      logger "down 2X in a row, rebooting"
      /sbin/reboot
    fi
    cat ${TMPFILE} | logger
    touch /tmp/downfile
  fi
else
  if [[ -f /tmp/downfile ]];then
    logger "recovered from a down network"
    rm -f /tmp/downfile
  fi
fi
